package com.witmore.neutron.ai.web.a_cognitive;

import com.alibaba.fastjson.JSONArray;
import com.jk.aliyun.oss.JkOssClient;
import com.jk.common.response.ResponseResult;
import com.witmore.neutron.ai.api.dto.ContentDTO;
import com.witmore.neutron.ai.api.dto.MessageContentDTO;
import com.witmore.neutron.ai.web.controller.bo.MessageBO;
import com.witmore.neutron.ai.web.service.ChatClientRouterService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.codec.ServerSentEvent;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import reactor.core.publisher.Flux;

import java.util.ArrayList;
import java.util.List;

import static com.witmore.neutron.ai.web.constants.CommonConstant.OSS_FILE_UPLOAD_TP_PREFIX;
import static java.lang.String.format;

/**
 * Description: ChatController
 * Author: 豆子高
 * Date: 2025/5/29 16:03
 */
@Slf4j
@RestController
@RequestMapping("/cognitive/chat")
public class AiChatController {

    @Autowired
    private JkOssClient ossClient;

    @Autowired
    private ChatClientRouterService chatClientRouterService;


    @GetMapping("/ask")
    public ResponseResult<?> ask(@RequestParam("question") String question) {
        MessageBO messageBO = new MessageBO();
        messageBO.setStream(false);
        messageBO.setMessages(this.getMessages("azF8HktJBnAlUkuo", null, question));
        messageBO.setAgentId(59);
        messageBO.setAgentCode("azF8HktJBnAlUkuo");
        messageBO.setSource("web");
        messageBO.setSessionId("豆子高测试456789"); // 示例会话ID
        return chatClientRouterService.routeRequest(messageBO);
    }

    @GetMapping("/askMedia")
    public ResponseResult<?> askMedia(@RequestParam("question") String question) {
        MessageBO messageBO = new MessageBO();
        messageBO.setStream(false);
        messageBO.setMessages(this.getMessages("1748575059884", null, question));
        messageBO.setAgentId(58);
        messageBO.setAgentCode("1748575059884");
        messageBO.setSource("web");
        messageBO.setSessionId("34567-4567898765-234568765-34");
//        messageBO.setUrl("https://witmore.oss-cn-hangzhou.aliyuncs.com/agent/test/test.png");
        messageBO.setMaxMessages(10);
        return chatClientRouterService.routeRequest(messageBO);
    }

    @GetMapping(value = "/askStream", produces = "text/event-stream;charset=utf-8")
    public Flux<ServerSentEvent<String>> askStream(@RequestParam("question") String question) {
        // 这里可以调用AI模型进行问答
        MessageBO messageBO = new MessageBO();
        messageBO.setStream(true);
        messageBO.setMessages(this.getMessages("azF8HktJBnAlUkuo", null, question));
        messageBO.setAgentId(59);
        messageBO.setAgentCode("azF8HktJBnAlUkuo");
        messageBO.setSource("web");
        messageBO.setSessionId("豆子高测试456789r493r94i"); // 示例会话ID
        return chatClientRouterService.routeRequestSSEStream(messageBO);
    }


    private List<MessageContentDTO> getMessages(String agentCode, MultipartFile file, String message) {
        List<MessageContentDTO> messages = new ArrayList<>();
        // user角色的消息
        MessageContentDTO contentDTO = new MessageContentDTO();
        contentDTO.setRole("user");
        List<ContentDTO> contentList = new ArrayList<>();
        // user角色的消息 - 文本内容
        ContentDTO textContent = new ContentDTO();
        textContent.setType("text");
        textContent.setText(StringUtils.isEmpty(message) ? "（用户未提供输入）" : message);
        contentList.add(textContent);

        // user角色的消息 - 图片内容
        if (file != null && file.isEmpty()) {
            try {
                String fileName = format(OSS_FILE_UPLOAD_TP_PREFIX, agentCode) + System.currentTimeMillis() + ".jpg";
                String url = ossClient.uploadFile(fileName, file);
                ContentDTO imageContent = new ContentDTO();
                imageContent.setType("image_url");
                imageContent.setUrl(url);
                contentList.add(imageContent);

            } catch (Exception e) {
                throw new RuntimeException("图片上传失败: " + e.getMessage(), e);
            }
        }
        contentDTO.setContent(JSONArray.toJSONString(contentList));
        messages.add(contentDTO);
        return messages;
    }
}
